<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }" class="bigCard">
    <template #header>
      <div>
        <el-button type="primary" icon="ele-Plus" @click="add">添加</el-button>
      </div>
    </template>
    <!-- 表格 -->
    <el-table :data="trademarkList" border stripe v-loading="loading">
      <el-table-column type="index" width="80" label="序号" />
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="图片logo" prop="logoUrl">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" alt="" height="100" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            type="warning"
            size="default"
            icon="ele-Edit"
            @click="edit(row)"
            >修改</el-button
          >
          <el-popconfirm title="确认删除吗?" @confirm="delTrademark(row.id)">
            <template #reference>
              <el-button type="danger" size="default" icon="ele-Delete"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      :style="{ marginTop: '20px' }"
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 7, 9]"
      :total="totalNum"
      layout="total, prev, pager, next, sizes"
      background
    >
    </el-pagination>
    <!-- 添加对话框 -->
    <el-dialog
      :title="tmInfo.id ? '修改品牌' : '新增品牌'"
      v-model="dialogVisible"
      width="60%"
    >
      <el-form
        label-width="80px"
        :inline="false"
        :model="tmInfo"
        :rules="rules"
        ref="ruleFormRef"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="tmInfo.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌logo" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${baseUrl}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><ele-Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addOrUpdateTrademark">{{
            tmInfo.id ? "修改" : "新增"
          }}</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import type { trademarkItemType } from "@/api/trademark";

export default defineComponent({
  name: "Trademark",
});
</script>

<script setup lang="ts">
import { ref, onMounted, watch, reactive } from "vue";
import type { trademarkIlistType } from "@/api/trademark";
import {
  reqTrademarkInfo,
  reqAddTrademark,
  reqUpdateTrademark,
  reqDeleteTrademark,
} from "@/api/trademark";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules, UploadProps } from "element-plus";

// 列表数据
const trademarkList = ref<trademarkIlistType>([]);
// 当前页
const currentPage = ref(1);
// 每页数据条数
const pageSize = ref(3);
// 总条数
const totalNum = ref(0);
// loading效果
const loading = ref(false);

const getTrademarkList = async () => {
  try {
    loading.value = true;
    const result = await reqTrademarkInfo(currentPage.value, pageSize.value);
    trademarkList.value = result.records;
    totalNum.value = result.total;
    loading.value = false;
  } catch (error: any) {
    ElMessage.error("请求列表错误:" + error.message);
  }
};
onMounted(() => {
  getTrademarkList();
});
watch([pageSize, currentPage], () => {
  getTrademarkList();
  window.scrollTo(0, 0);
});

//dialog弹窗的数据
const dialogVisible = ref(false);
//图片地址
const imageUrl = ref("");
// 接口前缀
const baseUrl = import.meta.env.VITE_API_URL;
// 定义收集表单数据
const tmInfo = ref<trademarkItemType>({
  tmName: "",
  logoUrl: "",
});

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // console.log(response, uploadFile, URL.createObjectURL(uploadFile.raw!));
  //URL.createObjectURL(uploadFile.raw!):拿到被被上传图片在本地服务器缓存的地址
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  tmInfo.value.logoUrl = response.data;
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (!rawFile.type.startsWith("image/")) {
    ElMessage.error("上传的不是图片文件!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("图片不能大于10MB!");
    return false;
  }
  return true;
};
/**
 * 添加和修改品牌
 */
// 定义表单提交校验
const ruleFormRef = ref<FormInstance>();
const addOrUpdateTrademark = async () => {
  // 表单提交校验
  try {
    await ruleFormRef.value?.validate();
  } catch (error) {
    return;
  }
  if (tmInfo.value.id) {
    try {
      await reqUpdateTrademark(tmInfo.value);
      dialogVisible.value = false;
      getTrademarkList();
    } catch (error: any) {
      ElMessage.error("修改失败" + error.message);
    }
  } else {
    try {
      await reqAddTrademark(tmInfo.value);
      dialogVisible.value = false;
      getTrademarkList();
    } catch (error: any) {
      ElMessage.error("添加失败" + error.message);
    }
  }
};
/**
 * 用户点击添加按钮的回调
 */
const add = () => {
  ruleFormRef.value?.clearValidate();
  dialogVisible.value = true;
  tmInfo.value = {
    tmName: "",
    logoUrl: "",
  };
  imageUrl.value = "";
};
/**
 * 点击修改触发的回调函数
 */
const edit = (row: trademarkItemType) => {
  ruleFormRef.value?.clearValidate();
  dialogVisible.value = true;
  tmInfo.value = { ...row };
  imageUrl.value = row.logoUrl;
};
/**
 * 点击确认删除触发的函数
 */
const delTrademark = async (id: number) => {
  try {
    await reqDeleteTrademark(id);
    getTrademarkList();
  } catch (error: any) {
    ElMessage.error("删除失败" + error.message);
  }
};
/**
 * 表单校验
 */
// 自定义校验规则
const validatePass = (rule: any, value: any, callback: any) => {
  const reg = /^.{2,6}$/;
  if (reg.test(value)) {
    callback();
  } else {
    callback(new Error("品牌长度必须是2-6位字符"));
  }
};
const rules = reactive<FormRules>({
  // 自定义校验
  tmName: [{ required: true, validator: validatePass, trigger: "blur" }],
  // 系统校验
  logoUrl: [{ required: true, message: "品牌logo不能为空", trigger: "blur" }],
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.bigCard >>> .el-dialog {
  margin-top: 50px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>